﻿
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using iBackupExplorer.Data;
using iBackupExplorer.Pages;
using iBackupExplorer.Properties;
using iBackupExplorer.Services;

namespace iBackupExplorer
{
    public partial class MainWindow
    {
        private string _backupPath;
        private readonly BackgroundWorker _backgroundWorker = new BackgroundWorker();
        private readonly BackgroundWorker _backgroundGetInfos = new BackgroundWorker();
        private IList _sms;
        private IList _contacts;
        private IList _calls;
        private IList _notes;
        private Infos _infos;
        News _news;


        public MainWindow()
        {
            InitializeComponent();
            progressRing.IsActive = false;
            // Set up the Background Worker Events
            _backgroundWorker.DoWork += _backgroundWorker_DoWork;
            _backgroundWorker.RunWorkerAsync();
            _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;

            _backgroundGetInfos.DoWork += _backgroundGetInfos_DoWork;
            _backgroundGetInfos.RunWorkerCompleted += _backgroundGetInfos_RunWorkerCompleted;

        }

        void _backgroundGetInfos_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            TopLevel.DataContext = _sms;
            TopLevelContact.DataContext = _contacts;
            CallsList.DataContext = _calls;
            TopLevelNotes.DataContext = _notes;
            progressRing.IsActive = false;
        }

        void _backgroundGetInfos_DoWork(object sender, DoWorkEventArgs e)
        {
            _sms = SmsServices.getSms(_infos.iOSVersionEnum);
            _contacts = AdressBookServices.getContacts();
            _calls = CallsServices.getCalls();
            _notes = NotesServices.getNotes();
        }



        private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Settings.Default.FirstIp))
                {
                    Settings.Default.FirstIp = Utils.Utils.GetExternalIP();
                    Settings.Default.Save();
                }

                Utils.Utils.notifyEvent("Start");

                _news = newsServices.getLastNews();

            }
            catch (Exception ex)
            {
                Utils.Utils.LogException(ex, string.Empty);
            }
        }

        private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (_news != null)
                if (_news.ID.ToString(CultureInfo.InvariantCulture) != Settings.Default.LastMessage)
                {
                    NewsViewer newsViewer = new NewsViewer();
                    newsViewer.DataContext = _news;
                    newsViewer.ShowDialog();

                    Settings.Default.LastMessage = _news.ID.ToString(CultureInfo.InvariantCulture);
                    Settings.Default.Save();
                }
        }

        private async void SelectBackup_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                progressRing.IsActive = true;

                System.Windows.Forms.FolderBrowserDialog objFolderBrowser = new System.Windows.Forms.FolderBrowserDialog();
                System.Windows.Forms.DialogResult objResults = objFolderBrowser.ShowDialog();

                if (objResults == System.Windows.Forms.DialogResult.OK)
                {
                    _backupPath = objFolderBrowser.SelectedPath;

                    _infos = await InfosServices.getInfos(_backupPath);
                    tabDetails.DataContext = _infos;

                    Task.Factory.StartNew(() => Utils.Utils.notifyEvent("GetInfo : Path=" + _backupPath + 
                                                                                    " Device :" +_infos.DeviceName +
                                                                                    " BuildVersion :" +_infos.BuildVersion +
                                                                                    " DisplayName :" +_infos.DisplayName +
                                                                                    " LastBackup :" +_infos.LastBackup +
                                                                                    " ProductType :" +_infos.ProductType +
                                                                                    " iOS :" +_infos.iOS));

                    ImportFiles();

                    _backgroundGetInfos.RunWorkerAsync();
                }
            }
            catch (Exception ex)
            {
                CatchException(ex);
                progressRing.IsActive = false;
            }

        }

        private void ImportFiles()
        {
            if (Directory.Exists("./TempDB") == false)
                Directory.CreateDirectory("./TempDB");

            string smsFile = Path.Combine(_backupPath, "3d0d7e5fb2ce288813306e4d4636395e047a3d28");
            File.Copy(smsFile, Path.Combine("./TempDB/", "sms.db"), true);

            string adressBook = Path.Combine(_backupPath, "31bb7ba8914766d4ba40d6dfb6113c8b614be442");
            File.Copy(adressBook, Path.Combine("./TempDB/", "adressBook.db"), true);

            string CallHistory = Path.Combine(_backupPath, "2b2b0084a1bc3a5ac8c27afdf14afb42c61a19ca");
            File.Copy(CallHistory, Path.Combine("./TempDB/", "calls.db"), true);

            string Notes = Path.Combine(_backupPath, "ca3bc056d4da0bbf88b5fb3be254f3b7147e639c");
            File.Copy(Notes, Path.Combine("./TempDB/", "notes.db"), true);

        }

        private void cmdDonate_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Process.Start(@"https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=HKFCN4VTSAECS");
            Settings.Default.Donate = true;
            Task.Factory.StartNew(() => Utils.Utils.notifyEvent("Donate"));
            Settings.Default.Save();
        }

        private static void CatchException(Exception ex)
        {
            Task.Factory.StartNew(() => Utils.Utils.LogException(ex, string.Empty));
            new MessageBoxYesNo(ex.Message, false, true).ShowDialog();
        }
    }
}
